<?php

namespace App\Services;

use App\AccessLog;
use Illuminate\Support\Facades\DB;

/**
 * Class PuvService
 *
 * @package \App\Services
 */
class PuvService
{

    /**
     * 根据appId和日期获取pu uv ip
     * @param $appId
     * @param $date
     *
     * @return array
     */
    public function getPuvByAppId($appId, $date)
    {
        $data = [];
        // 获取今日pv 和uv 和访问ip数目
        $data['pv'] = AccessLog::where("app_id", $appId)->where("access_date", $date)
                            ->count();
        $firstCount = AccessLog::where("app_id", $appId)->where("access_date", $date)
                ->where("cookie_value", "")->count();

        $twoCount = AccessLog::select('cookie_value')->where("app_id", $appId)
                    ->where("access_date", $date)
                        ->where("cookie_value", "<>", "")->count(DB::raw("distinct(cookie_value)"));

        $data['uv'] = $twoCount + $firstCount;
        $data['ip'] = AccessLog::select('visitor_ip')->where("app_id", $appId)
            ->where("access_date", $date)
                ->count(DB::raw("distinct(visitor_ip)"));

        return $data;
    }

    /**
     * 根据channelId和日期获取pu uv ip
     * @param $channelId
     * @param $date
     * @param $appId
     * @return array
     */
    public function getPuvByChannelId($channelId, $date, $appId = 0)
    {
        $data = [];
        // 获取今日pv 和uv 和访问ip数目
        $data['pv'] = AccessLog::where("channel_id", $channelId)->where("access_date", $date)
                        ->count();


        // 小林2 channel单独处理
        if ($appId == 288) {
            $firstCount = AccessLog::select('visitor_ip')->where("channel_id", $channelId)->where("access_date", $date)
                ->where("cookie_value", "")->count(DB::raw("distinct(visitor_ip)"));
        } else {
            $firstCount = AccessLog::where("channel_id", $channelId)->where("access_date", $date)
                ->where("cookie_value", "")->count();
        }


        $twoCount = AccessLog::select('cookie_value')->where("channel_id", $channelId)->where("access_date", $date)
            ->where("cookie_value", "<>", "")->count(DB::raw("distinct(cookie_value)"));

        $data['uv'] = $twoCount + $firstCount;

        // 优化 uv
//        $sql = "select count(*) as total from (select count(*) FROM ya_access_logs where access_date=:access_date GROUP BY visitor_ip,cookie_value) s";
//        $data['uv'] = DB::selectOne($sql, [":access_date" => $date])->total;


        $data['ip']  = AccessLog::select('visitor_ip')->where("channel_id", $channelId)->where("access_date", $date)
            ->count(DB::raw("distinct(visitor_ip)"));

        return $data;
    }
}
